package com.itheima.web.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.itheima.domain.User;
import com.itheima.service.UserService;

public class UserServlet extends BaseServlet {
	
	//用户注销
	public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		//从session中将user删除
		session.removeAttribute("user");
		response.sendRedirect(request.getContextPath()+"/login.jsp");
	}
	//登录
	public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		//获取数据
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		UserService service= new UserService();
		User user =null;
		try {
			 user =service.login(username,password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(user!=null){
			//登录成功
			//将登录的用户user对象存到session中
			session.setAttribute("user", user);
			response.sendRedirect(request.getContextPath());
		}else{
			request.setAttribute("loginInfo", "用户名或密码错误");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}